package com.jyu.reggie.controller;

import com.jyu.reggie.common.R;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {
    @Value("${reggie.path}")
    private String basePath;

    /**
     * @description: 文件上传方法
     * @param file
     * @return: com.jyu.reggie.common.R<java.lang.String>
     * @date: 2023/7/27 14:19
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file)  {
        log.info(file.toString());

        // 原文件名
        String originalFilename = file.getOriginalFilename();

        // 截取原文件后缀名
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        String fileName = UUID.randomUUID().toString() + suffix;

        File dir = new File(basePath);

        if( !dir.exists()) {
            dir.mkdirs();
        }

        try {
            file.transferTo(new File(basePath + fileName));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return R.success(fileName);
    }

    @GetMapping("/download")
    public void downLoad(String name, HttpServletResponse response){
        try {
            // 输入流，读取文件内容
            FileInputStream fis = new FileInputStream(new File(basePath + name));

            ServletOutputStream os = response.getOutputStream();

            response.setContentType("image/jpeg");

            byte[] bytes = new byte[1024];
            int len = 0;
            while ( (len = fis.read(bytes)) != -1){
                os.write(bytes,0, len);
                os.flush();
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

}
